package com.fuze.energy.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author sepc_
 * @date 8/16/2021 14:55
 * Netty TCP连接配置
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class TcpServer {

    private static final int PORT = 9001;
    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private final ServerBootstrap serverBootstrap;
    private ChannelFuture channelFuture;

    public static TcpServer getInstance() {
        return TcpServer.NettyTcpServerHolder.INSTANCE;
    }

    private static final class NettyTcpServerHolder {
        static final TcpServer INSTANCE = new TcpServer();

        private NettyTcpServerHolder() {
        }
    }


    private TcpServer() {
        this.bossGroup = new NioEventLoopGroup();
        this.workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(this.bossGroup, this.workerGroup);
        this.serverBootstrap.channel(NioServerSocketChannel.class);
        this.serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        this.serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
        this.serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        this.serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        this.serverBootstrap.childHandler(new NettyServerInitializer());
    }

    /**
     * 启动方法
     */
    public void start() {
        try {
            this.channelFuture = this.serverBootstrap.bind("0.0.0.0", PORT).sync();
            log.warn("netty TCP服务启动: [port:" + PORT + "]");
            this.channelFuture.channel().closeFuture().sync();
        } catch (Exception var5) {
            log.error("netty服务启动异常-" + var5.getMessage());
        } finally {
            this.bossGroup.shutdownGracefully();
            this.workerGroup.shutdownGracefully();
        }

    }

}
